//
//  QRCodeView.swift
//  NJU QR
//
//  Created by 许煜恒 on 8/14.
//

import SwiftUI
import QRCode
import QRCodeExternal

struct QRCodeView: View {
    @Environment(\.colorScheme) var appearance
    var qr_content: QrContentExtractor
    
    var doc:QRCode.Document {
        let d=QRCode.Document(generator: QRCodeGenerator_External(), data: qr_content.qrcode.data(using: .utf8))
        let _=d.design.foregroundColor(qr_content.color)
        let _=d.design.backgroundColor(.init(red: 1, green: 1, blue: 1, alpha: 1))

        return d
    }
    
    var body: some View {
        GeometryReader{geometry in
            let length=min(geometry.size.width,geometry.size.height)
            let overRender=2.0
            if let uii=doc.uiImage(CGSize(width: length*overRender, height: length*overRender))?.resizableImage(withCapInsets: .zero){
                    Image(uiImage: uii)
                        .scaleEffect(1.0/overRender)
                        .frame(width: length, height: length, alignment: .center)
            }else{
                Text("Failed to generate QR code")
            }
        }
        .scaledToFit()
        .padding()

    }
}

struct QRCodeView_Previews: PreviewProvider {
    static var previews: some View {
        QRCodeView(qr_content: QrContentExtractor(qrcode: test_qr_content, qrcodeColor: "绿码"))
        
    }
}
